<template>
	<view class="container">
		<view class="flex diygw-autoview diygw-col-24 flex-direction-column autoview-clz">
			<!-- #ifdef MP-WEIXIN -->
			<view class="diygw-absolute autoview_0">
				<view class="flex diygw-col-18 search-clz">
					<view class="diygw-search">
						<view class="flex1 align-center flex padding-xs solid radius">
							<text class="diy-icon-search" style="color: "></text>
							<input class="flex1" name="search" type="" v-model="name" @confirm="searchByName"
								@input="searchByName" placeholder="请输入电话或者商品名称" />
						</view>
						<view @click="searchByName" style="color: #333 !important"
							class="diygw-tag margin-left-xs radius-xs"> 搜索 </view>
					</view>
				</view>
			</view>
			<view class="search-filter" @tap="orderbyChange" :class="{'text-theme': hasChoose}">
				<image class="search-filter-image" src="https://www.dtxtkj.com/app/images/filter.png"></image>
			</view>
			<fjj-condition ref='condition' @touchmove.stop :color="color" :list="filterData"
				:defaultValue="defaultValue" @result="resultConditon" />
			<!--  #endif -->
		</view>

		<!-- 订单列表 -->
		<!-- 	<view class="uni-padding-wrap uni-common-mt">
			<text v-for="(value, index) in filterlist" :key="rowIndex">
				{{value}}
			</text>
		</view> -->

		<view class="data-list">
			<view v-for="(item, rowIndex) in dataList" :key="rowIndex">
				<view class="data-item" @click="goToDetail(item)">
					<img :src="goodImage(item)" class="data-image" @error="handleImageError(item)" />
					<view class="data-info">
						<text class="data-name">
							<text>{{ item.goodsName ? item.goodsName : '商品名称' }}</text>
							<text style="padding-left:20rpx;font-size: 25rpx;color: gray;">
								X{{item.orderNum}}
							</text>
							<text class="data-name-right">￥{{item.orderAmount}}</text>
						</text>
						<text class="data-info-detail">订单来源：{{ sourceOpt[item.source] }}</text>
						<text v-if="item.returnNum"  class="data-info-detail">退货数量：{{ item.returnNum }}</text>
						<text class="data-info-detail">
							<text v-if="item.orderNum - item.outNum > 0">待出库:{{ item.orderNum - item.outNum }}</text>
							<text v-if="item.unpaid" style="padding-left:20rpx">待付款:{{ item.unpaid }}</text>
						</text>
						<text class="data-info-detail">
							<text class="data-info-status">{{payStatusOpt[item.payStatus]}}</text>
							<text class="data-info-status">{{statusOpt[item.status] }}</text>
						</text>
					</view>
				</view>
				<view class="data-item-btn" v-if="userInfo.roleId !='1001'">
					<button class="btn delete" @click="deleteObj(item)">删除</button>
					<!-- <button class="btn view" @click="goToDetail(item)">编辑</button> -->
					<button v-if="item.payStatus == 0 " class="btn out" @click="showPayDialog(item)">付款</button>
					<button v-else-if="item.status == 0 || item.status == 1 " class="btn out"
						@click="showEditDialog(item)">取货</button>
					<button v-else-if="item.status == 2 && item.orderNum - (item.returnNum ? item.returnNum : 0) > 0" class="btn out" @click="showReturnDialog(item)">退货</button>
				</view>
			</view>
		</view>
		<!-- <view class="flex diygw-col-24">
			<view class="diygw-pzx" style="border-bottom: 1rpx solid #8e8d8d;"></view>
		</view> -->
		<!-- 修改数量的弹窗 -->
		<uni-popup ref="editPopup" type="dialog">
			<view class="out-popup">
				<view class="out-popup-title"> 商品出库 </view>
				<view class="out-popup-num">
					<text>出库数量：</text>
					<uni-number-box :min="0" :max="max" v-model="editQuantity" />
				</view>
				<view class="out-popup-btn">
					<button class="btn cancel" @click="cancelEdit()">取消</button>
					<button class="btn config" @click="confirmEdit()">确认</button>
				</view>
			</view>
		</uni-popup>

		<!-- 修改付款数量弹窗 -->
		<uni-popup ref="payDialog" type="dialog">
			<view class="out-popup">
				<view class="out-popup-title"> 付款界面 </view>
				<view class="out-popup-num">
					<text>付款：￥</text>
					<uni-number-box :min="0.00" :max="max" v-model="editQuantity" />
				</view>
				<view class="out-popup-btn">
					<button class="btn cancel" @click="cancelPayDialog()">取消</button>
					<button class="btn config" @click="payConfirmEdit()">确认</button>
				</view>
			</view>
		</uni-popup>

		<!-- 退货弹窗 -->
		<uni-popup ref="returnDialog" type="dialog">
			<view class="out-popup">
				<view class="out-popup-title"> 退货 </view>
				<view class="out-popup-num">
					<text>退货数量</text>
					<uni-input <uni-number-box :min="0.00" :max="max" v-model="editQuantity" />
				</view>
				<view class="out-popup-num">
					<text>是否退款：</text>
					<uni-data-checkbox v-model="orderRefund.returnToUser" :localdata="returnOptions" />
				</view>
				<view class="out-popup-num" v-if="orderRefund.returnToUser === 1">
					<text>退款类型：</text>
					<uni-data-checkbox v-model="orderRefund.returnType" :localdata="payOptions" />
				</view>
				<view class="out-popup-btn">
					<button class="btn cancel" @click="cancelReturnDialog()">取消</button>
					<button class="btn config" @click="refundConfirmEdit()">确认</button>
				</view>
			</view>
		</uni-popup>

		<view class="clearfix"></view>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapMutations
	} from 'vuex';
	import fjjCondition from '@/components/fjj-condition/fjj-condition.vue';
	import filterData from '@/common/data/orders/order_filter.js';
	import dataDictionary from '@/common/data/dataDictionary.js';
	import roleAuth from '@/common/data/role_auth/roleauth.js';
	export default {
		data() {
			return {
				color: '#4D7BFE',
				name: '',
				hasChoose: false,
				filterData: filterData,
				goodsOpt: dataDictionary.goods || [],
				ordersOpt: dataDictionary.orders || [],
				sourceOpt: {},
				payStatusOpt: {},
				statusOpt: {},
				searchParam: {
					userId: null,
					storeIds: [],
					payStatusList: [],
					statusList: [],
					startDate: null,
					endDate: null,
				},
				defaultValue: {},
				returnOptions: [{
						value: 0,
						text: "将钱充到会员卡上"
					},
					{
						value: 1,
						text: "退款"
					}
				],
				payOptions: [{
						value: 1,
						text: "现金"
					},
					{
						value: 2,
						text: "微信"
					}, {
						value: 3,
						text: "支付宝"
					}
				],
				
				orderRefund:{
					returnToUser: 0, //不退款,将钱充到用户会员卡上
					returnType:1,
					refundNum:0
				}, 

				items: ['所有订单', '待付款', '待取货'],
				current: 0,
				activeColor: '#007aff',

				backDataList: [],
				dataList: [],
				goodList: [],
				isLoading: false,
				loadingText: '加载中...',
				isNoData: false,
				pageCurrent: 1,
				showNoDataTip: false,

				editQuantity: 0,
				item: {},
				max: 0,
				isReturn: false,
				roleAuth: roleAuth,
				defaultImage: 'static/no_image.png',
			};
		},

		components: {
			fjjCondition,
		},

		computed: {
			...mapGetters({
				userInfo: 'user/info',
				hasLogin: 'user/hasLogin'
			}),
		},

		onShow() {
			this.setCurrentPage(this);
		},
		onLoad(option) {
			this.setCurrentPage(this);
			if (option) {
				// 仅查询用户自己的订单数据
				if (option.userId) {
					this.searchParam.userId = option.userId;
				}
				if (option.payStatus) {
					this.searchParam.payStatusList.push(parseInt(option.payStatus));
					this.defaultValue.payStatus = this.searchParam.payStatusList;
				} else if (option.status) {
					let statusList = option.status.split(";");
					for (let status in statusList) {
						this.searchParam.statusList.push(parseInt(status));
					}
					this.defaultValue.status = this.searchParam.statusList;
				} else {
					this.onSearch();
				}

				// 获取用户的门店权限
				if (this.userInfo?.storeIds) {
					this.searchParam.storeIds = this.userInfo?.storeIds;
				}

				this.setData({
					globalOption: this.getOption(option)
				});
			}

			// 初始化枚举值
			this.initOpt();

			// 过滤值初始化
			this.initFilterData()
		},
		methods: {
			initOpt() {
				if (this.ordersOpt) {
					let statusOpts = this.ordersOpt.status;
					for (let i = 0; i < statusOpts.length; i++) {
						this.statusOpt[statusOpts[i].value] = statusOpts[i].text;
					}
					let payStatusOpts = this.ordersOpt.payStatus;
					for (let i = 0; i < payStatusOpts.length; i++) {
						this.payStatusOpt[payStatusOpts[i].value] = payStatusOpts[i].text;
					}

					let sourceOpts = this.ordersOpt.source;
					for (let i = 0; i < sourceOpts.length; i++) {
						this.sourceOpt[sourceOpts[i].value] = sourceOpts[i].text;
					}
				}
			},

			goodImage(item) {
				if (item.goodsImage) {
					return this.$urlConfig + '/api/images/' + item.goodsImage;
				}
				return this.$urlConfig + '/api/images/' + this.defaultImage;
			},

			/**
			 * 初始化过滤枚举值
			 */
			async initFilterData() {
				if (this.filterData) {
					for (let i = 0; i < this.filterData.length; i++) {
						if (this.ordersOpt[this.filterData[i].key]) {
							this.filterData[i].detailList = this.ordersOpt[this.filterData[i].key];
						} else if (this.goodsOpt[this.filterData[i].key]) {
							this.filterData[i].detailList = this.goodsOpt[this.filterData[i].key];
						}
					}
				}
			},

			/**
			 * @param {Object} obj
			 * 返回筛选值
			 */
			resultConditon(obj) {
				this.$refs.condition.visibleDrawer = false;
				this.hasChoose = obj.hasChoose;
				console.log("===========obj", obj);
				this.searchParam.payStatusList = obj.result.payStatus;
				this.searchParam.sources = obj.result.source;
				this.searchParam.statusList = obj.result.status;
				this.searchParam.sta = obj.result.order_at;
				this.onSearch();
			},

			orderbyChange(obj) {
				console.log("=======orderbyChange", 1);
				this.$refs.condition.visibleDrawer = true;
			},

			/**
			 * @param {Object} item
			 * 跳转到详情页
			 */
			goToDetail(item) {
				uni.navigateTo({
					url: `/pages/order/detail?id=${item.id}&formData=${JSON.stringify(item)}`,
				});
			},

			searchByName() {
				this.searchParam.name = this.name;
				this.onSearch();
			},

			onClickTab(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
				} else {
					return;
				}

				if (this.current === 0) {
					this.billtype = this.$constant.workNoteType.todo;
					this.checkstatus = 1;
				} else {
					this.billtype = this.$constant.workNoteType.done;
					this.checkstatus = 2;
				}
				this.initLoadMoreData();
				this.queryFormList();
			},

			initLoadMoreData() {
				this.showNoDataTip = false;
				this.isLoading = false;
				this.isNoData = false;
				this.pageCurrent = 1;
				this.dataList = [];
			},

			async onSearch() {
				;
				if (this.searchParam.userId && this.userInfo.id == this.searchParam.userId) {
					this.searchParam.phone = this.userInfo.tel
				}
				this.$api.ordersSearch(this.searchParam).then(result => {
					this.dataList = result ? result : []
				}).catch(res => {
					// 失败进行的操作
					uni.showToast({
						title: "查询失败!",
						duration: 3000
					});
					return;
				})
			},


			changeTabs(evt) {
				let {
					index
				} = evt.currentTarget.dataset;
				if (index == this.tabsIndex) return;
				this.setData({
					tabsIndex: index,
					tabsMainIndex: index
				});
				this.setTabsStatus(index);
				this.navigateTo({
					type: 'searchDataFunction'
				});
			},

			/**
			 * @param {Object} item
			 * 显示付款弹框
			 */
			showPayDialog(item) {
				this.item = item;
				this.editQuantity = item.unpaid;
				this.max = this.editQuantity;
				this.$refs.payDialog.open();
			},

			/**
			 * @param {Object} item
			 * 显示出库弹框
			 */
			showEditDialog(item) {
				this.editQuantity = item.orderNum - (item.returnNum ? item.returnNum : 0) - item.outNum;
				this.max = this.editQuantity;
				this.item = item;
				this.$refs.editPopup.open();
			},

			showReturnDialog(item) {
				this.editQuantity = item.orderNum - (item.returnNum ? item.returnNum : 0);
				this.max = this.editQuantity;
				this.item = item;
				this.$refs.returnDialog.open();
			},

			/**
			 * 修改付款信息
			 */
			async payConfirmEdit() {
				const newQuantity = parseInt(this.editQuantity);
				// 出库数量等于用户手动维护的数量加上已经出库的数量
				this.item.paid = this.item.paid + newQuantity;
				this.item.payStatus = this.item.order_amount == this.item.paid ? 1 : 0;
				try {
					uni.showLoading({
						title: "更新中..."
					});
					// 调用后端API更新数量
					this.$api.ordersSave(this.item).then(result => {
						this.onSearch();
						uni.hideLoading();
						// 成功处理
						uni.showToast({
							title: "付款成功",
							duration: 3000
						});
						// 关闭弹窗
						this.$refs.editPopup.close();
					}).catch(res => {
						uni.hideLoading();
						// 失败进行的操作
						uni.showToast({
							title: "付款失败!",
							duration: 3000
						});
						return;
					})
					// 如果需要刷新整个页面数据，可以调用这个方法
					// this.refreshData();

				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: "更新失败: " + error.message,
						icon: "none"
					});
				}
			},

			/**
			 * 确认修改
			 */
			async confirmEdit() {
				const newQuantity = parseInt(this.editQuantity);
				// 出库数量等于用户手动维护的数量加上已经出库的数量
				this.item.outNum = this.item.outNum + newQuantity;
				this.item.outStatus = this.item.outNum == this.item.orderNum ? 2 : 1
				if (this.item.outNum == this.item.orderNum) {
					// 已取货
					this.item.status = 2;
				}
				try {
					uni.showLoading({
						title: "更新中..."
					});

					// 调用后端API更新数量
					this.$api.ordersSave(this.item).then(result => {
						this.onSearch();
						uni.hideLoading();
						// 成功处理
						uni.showToast({
							title: "取货成功",
							duration: 3000
						});
						// 关闭弹窗
						this.$refs.editPopup.close();
					}).catch(res => {
						uni.hideLoading();
						// 失败进行的操作
						uni.showToast({
							title: "取货失败!",
							duration: 3000
						});
						return;
					})
					// 如果需要刷新整个页面数据，可以调用这个方法
					// this.refreshData();

				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: "更新失败: " + error.message,
						icon: "none"
					});
				}
			},
			
			/**
			 * 修改退货信息
			 */
			async refundConfirmEdit() {
				const newQuantity = parseInt(this.editQuantity);
				this.orderRefund["refundNum"] = newQuantity;
				this.orderRefund["refundMoney"] = this.item.goodsPrice * newQuantity;
				this.orderRefund["goodsId"] = this.item.goodsId;
				this.orderRefund["orderId"] = this.item.id;
				try {
					uni.showLoading({
						title: "更新中..."
					});
					// 调用后端API退货
					this.$api.orderGoodRefund(this.orderRefund).then(result => {
						debugger;
						this.onSearch();
						uni.hideLoading();
						// 成功处理
						uni.showToast({
							title: "退货成功",
							duration: 1000
						});
						// 关闭弹窗
						this.$refs.returnDialog.close();
					}).catch(res => {
						uni.hideLoading();
						// 失败进行的操作
						uni.showToast({
							title: "退货失败!",
							duration: 1000
						});
						return;
					})
					// 如果需要刷新整个页面数据，可以调用这个方法
					// this.refreshData();
			
				} catch (error) {
					uni.hideLoading();
					uni.showToast({
						title: "退货失败: " + error.message,
						icon: "none"
					});
				}
			},

			// 取消修改
			cancelEdit() {
				this.$refs.editPopup.close();
			},

			cancelPayDialog() {
				this.$refs.payDialog.close();
			},

			// 取消修改
			cancelReturnDialog() {
				this.$refs.returnDialog.close();
				// 恢复默认勾选
				this.isReturnMoney = 0;
			},

			/**
			 * @param {Object} id 订单ID
			 * @param {Object} quantity 出库数量
			 */
			updateOdersQuantity(id, quantity) {
				return new Promise((resolve, reject) => {
					// 这里应该是实际的API调用，以下是模拟代码
					setTimeout(() => {
						// 模拟成功响应
						resolve({
							code: 200,
							message: "更新成功"
						});

						// 模拟错误
						// reject(new Error("网络错误"));
					}, 1000);
				});
			},

			// 刷新页面数据
			refreshData() {
				// 这里可以重新获取商品数据
				console.log("刷新数据...");
				// 例如: this.fetchGoodsInfo();
			},

			deleteObj(item) {
				this.$api.ordersRemove(item.id).then(result => {
					// 失败进行的操作
					uni.showToast({
						title: "删除成功!",
						duration: 3000
					});
					this.feildData();
					return;
				}).catch(res => {
					// 失败进行的操作
					uni.showToast({
						title: "删除失败!",
						duration: 3000
					});
					return;
				})
			},

			handleImageError(item) {
				item.goodsImage = '/static/no_image.png';
			},

		}

	};
</script>

<style lang="less" scoped>
	@import url("@/common/css/list_new.less");
</style>

<style lang="less" scoped>
	.out-popup {
		padding: 20px;
		background-color: #fff;
		border-radius: 12px;
		box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
	}

	.out-popup-title {
		font-size: 18px;
		/* 大一点的字体 */
		font-weight: bold;
		text-align: center;
		/* 居中显示 */
		margin-bottom: 20px;
		color: #333;
	}

	.out-popup-num {
		display: flex;
		/* 使用flex布局让元素排在一行 */
		align-items: center;
		/* 垂直居中 */
		margin-bottom: 20px;
	}

	.out-popup-num text {
		font-size: 14px;
		color: #666;
		margin-right: 10px;
		/* 给数字输入框留出间距 */
		white-space: nowrap;
		/* 防止文字换行 */
	}

	.out-popup-btn {
		display: flex;
		/* 使用flex布局让按钮排在一行 */
		justify-content: space-between;
		/* 按钮之间平均分布 */
	}

	.out-popup-btn .btn {
		flex: 1;
		/* 让两个按钮平分宽度 */
		margin: 0 5px;
		/* 按钮之间的间距 */
		height: 40px;
		line-height: 40px;
		border-radius: 6px;
		font-size: 14px;
		height: 64rpx;
		line-height: 1;
		align-items: center;
		display: inline-flex;
		justify-content: center;
		text-align: center;
		text-decoration: none;
		-webkit-transform: translate(0px, 0px);
		border-radius: 200rpx;
	}

	.out-popup-btn .cancel {
		background-color: #f8f8f8;
		color: #666;
		border: 1px solid #eaeaea;
	}

	.out-popup-btn .config {
		background-color: #007aff;
		color: #fff;
		border: 1px solid #007aff;
	}
</style>